<template>
  <div class="login-page">
    <h2>{{ siteName }}</h2>
    <form @submit.prevent="onSubmit">
      <div class="field"><label>用户名</label><input v-model="username" /></div>
      <div class="field"><label>密码</label><input type="password" v-model="password" /></div>
  <div class="actions">
        <button type="submit" style="width:318px;height:30px;cursor:pointer">登录</button>
      </div>
      <p v-if="error" class="error">{{ error }}</p>
    </form>
   
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useMenuStore } from '../stores/menu'
const loading = ref(false)
const username = ref('')
const password = ref('')
const error = ref('')
const router = useRouter()
const route = useRoute()
const auth = useAuthStore()
const menu = useMenuStore()

// site name loaded from backend (public endpoint)
const siteName = ref('')
async function loadSiteName() {
  try {
    const res = await fetch('/public/site-name')
    if (!res.ok) return
    const body = await res.json().catch(() => ({}))
    if (body && body.value) siteName.value = body.value
  } catch (e) {
    // fallback to default
  }
}

onMounted(() => {
  loadSiteName()
})

async function onSubmit() {
  error.value = ''
  try {
    await auth.login(username.value, password.value)
    // fetch menus after login
    try { await auth.fetchMenus() } catch (e) { /* ignore */ }
    // ensure sidebar is hidden immediately after login and set the active top menu to Dashboard
    try {
      menu.setShowSidebar(false)
      menu.setActiveTop('Dashboard')
    } catch (e) { /* ignore if store methods missing */ }
    // always redirect to dashboard and mark first top menu active
    window.localStorage.setItem('activeTopMenu', '0')
    router.replace('/dashboard')
  } catch (e: any) {
    error.value = e.message || 'Login failed'
  }
}
</script>

<style scoped>
.login-page { max-width:360px; margin:260px auto; padding:20px; border:1px solid #eee; border-radius:6px }
.field { margin-bottom:12px }
.field label { display:block; font-size:13px; margin-bottom:6px }
.field input { width:100%; padding:8px; box-sizing:border-box }
.actions { text-align:right;width:200px;margin-top:20px }
.error { color:#d9534f; margin-top:10px }
</style>